package com.superbit.web.utils;


import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * 通用工具类
 * @author 刘鑫/孟繁祺
 * @version 20170325
 */
public class CommonUtil {
	
	/**
	 * 获取用户真实IP地址
	 * @param request
	 * @return
	 */
	public static String getRemoteHost(javax.servlet.http.HttpServletRequest request){
		String ip = request.getHeader("x-forwarded-for");
	    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
	        ip = request.getHeader("Proxy-Client-IP");
	    }
	    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
	        ip = request.getHeader("WL-Proxy-Client-IP");
	    }
	    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
	        ip = request.getRemoteAddr();
	    }
	    return ip.equals("0:0:0:0:0:0:0:1")?"127.0.0.1":ip;
	}
	
	/**
	 * MD5加密
	 * @param content
	 * @return
	 */
	public static String EncoderByMd5(String content){
		// 生成一个MD5加密计算摘要
        MessageDigest md;
		try {
			md = MessageDigest.getInstance("MD5");
			// 计算md5函数
			md.update(content.getBytes());
	        // digest()最后确定返回md5 hash值，返回值为8为字符串。因为md5 hash值是16位的hex值，实际上就是8位的字符
	        // BigInteger函数则将8位的字符串转换成16位hex值，用字符串来表示；得到字符串形式的hash值
        	return new BigInteger(1, md.digest()).toString(16);
		} catch (NoSuchAlgorithmException e) {
			throw new RuntimeException("MD5加密出现错误");
		}
	}
	
	/**
	 * 手机区号校验
	 * @param areaCode	手机区号
	 * @return
	 */
	public static String areaCodeCheck(String areaCode) {
		if(areaCode.startsWith("+")) {
			areaCode = areaCode.substring(1);
		}
		if(areaCode.startsWith("00")) {
			areaCode = areaCode.substring(2);
		}
		return areaCode;
	}
	
}
